<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="关键字搜索" prop="search">
        <el-input v-model="queryParams.search" placeholder="关键字搜索" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['user:room:remove']">删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['user:room:export']">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="房主头像" align="center" prop="userPhoto">
        <template slot-scope="scope">
          <el-avatar :src="scope.row.userPhoto" />
        </template>
      </el-table-column>
      <el-table-column label="房间封面图" align="center" prop="coverImgUrl">
        <template slot-scope="scope">
          <img :src="scope.row.coverImgUrl" style="width: 80px;height: 60px;">
        </template>
      </el-table-column>
      <el-table-column label="房间id" align="center" prop="id" />
      <el-table-column label="房间号" align="center" prop="roomNumber" />
      <el-table-column label="房间名称" align="center" prop="name" />
      <el-table-column label="房间类型" align="center" prop="roomTypeName" />
      <el-table-column label="房间背景图" align="center" prop="backgroundUrl" />
      <el-table-column label="房间状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ scope.row.status == 0 ? '关闭' : scope.row.status == 1 ? "正常" : scope.row.status == 2 ? '封禁' : ""
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="房间介绍" align="center" prop="content" />
      <el-table-column label="聊天室编号" align="center" prop="groupId" />
      <el-table-column label="正在执行的动作" align="center" prop="motion" />
      <el-table-column label="关闭时间" align="center" prop="closeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.closeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['user:room:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['user:room:remove']">删除</el-button>

          <el-button size="mini" type="text" 
            @click="startMonitoring(scope.row.roomNumber, scope.row.soundNumber)">加入频道</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.size"
      @pagination="getList" />

    <!-- 添加或修改房间对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="0未删除1已删除" prop="isDel">
          <el-input v-model="form.isDel" placeholder="请输入0未删除1已删除" />
        </el-form-item>
        <el-form-item label="房间类型id" prop="roomTypeId">
          <el-input v-model="form.roomTypeId" placeholder="请输入房间类型id" />
        </el-form-item>
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="房间背景图" prop="backgroundUrl">
          <el-input v-model="form.backgroundUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="房间介绍">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="声网房间号" prop="soundNumber">
          <el-input v-model="form.soundNumber" placeholder="请输入声网房间号" />
        </el-form-item>
        <el-form-item label="融云群组编号" prop="groupId">
          <el-input v-model="form.groupId" placeholder="请输入融云群组编号" />
        </el-form-item>
        <el-form-item label="房间类型名称" prop="roomTypeName">
          <el-input v-model="form.roomTypeName" placeholder="请输入房间类型名称" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="正在执行的动作" prop="motion">
          <el-input v-model="form.motion" placeholder="请输入正在执行的动作" />
        </el-form-item>
        <el-form-item label="是否允许观众送礼0否1是" prop="isGive">
          <el-input v-model="form.isGive" placeholder="请输入是否允许观众送礼0否1是" />
        </el-form-item>
        <el-form-item label="是否默认开启连麦 0关闭1开启" prop="isConnect">
          <el-input v-model="form.isConnect" placeholder="请输入是否默认开启连麦 0关闭1开启" />
        </el-form-item>
        <el-form-item label="是否默认开启提问 0关闭1开启" prop="isQuiz">
          <el-input v-model="form.isQuiz" placeholder="请输入是否默认开启提问 0关闭1开启" />
        </el-form-item>
        <el-form-item label="关闭时间" prop="closeTime">
          <el-date-picker clearable v-model="form.closeTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择关闭时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="房主头像" prop="userPhoto">
          <el-input v-model="form.userPhoto" placeholder="请输入房主头像" />
        </el-form-item>
        <el-form-item label="房间封面图" prop="coverImgUrl">
          <el-input v-model="form.coverImgUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoom, getRoom, delRoom, addRoom, updateRoom } from "@/api/room/room";
import AgoraRTC from 'agora-rtc-sdk-ng';

export default {
  name: "Room",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房间表格数据
      roomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        search: ''
      },
      // 表单参数
      form: {},
      rtc: {
        localAudioTrack: null,
        client: null
      },
      appId: '37773b629876489a9201f5ae7447ffa8',
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.rtc.client = AgoraRTC.createClient({ mode: 'live', codec: 'vp8' });
    console.log("初始化SDK", this.client)
    this.rtc.client.on("user-published", async (user, mediaType) => {
      // Subscribe to the remote user when the SDK triggers the "user-published" event
      await this.rtc.client.subscribe(user, mediaType);
      console.log("subscribe success");

      // If the remote user publishes an audio track.
      if (mediaType === "audio") {
        // Get the RemoteAudioTrack object in the AgoraRTCRemoteUser object.
        const remoteAudioTrack = user.audioTrack;
        // Play the remote audio track.
        remoteAudioTrack.play();
      }
    });
    // Listen for the "user-unpublished" event
    this.rtc.client.on("user-unpublished", async (user) => {
      // Unsubscribe from the tracks of the remote user.
      await this.rtc.client.unsubscribe(user);
    });
  },
  methods: {
    closeRoomChannel() {
      rtc.localAudioTrack.close();
      // Leave the channel.
      rtc.client.leave();
    },
    async startMonitoring(channel, token) {
      try {
        await this.rtc.client.join(this.appId, channel, token, 0);
        this.rtc.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack();
        // Publish the local audio tracks to the RTC channel.
        await this.rtc.client.publish([this.rtc.localAudioTrack]);

      } catch (e) {
        console.error('Stream initialization or joining channel failed', e);
      }
    },
    /** 查询房间列表 */
    getList() {
      this.loading = true;
      listRoom(this.queryParams).then(response => {
        this.roomList = response.data.data;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        createTime: null,
        updateTime: null,
        remark: null,
        isDel: null,
        roomTypeId: null,
        userId: null,
        backgroundUrl: null,
        status: null,
        content: null,
        soundNumber: null,
        roomNumber: null,
        groupId: null,
        roomTypeName: null,
        longitude: null,
        latitude: null,
        motion: null,
        isGive: null,
        sex: null,
        isConnect: null,
        isQuiz: null,
        closeTime: null,
        userPhoto: null,
        coverImgUrl: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加房间";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRoom(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改房间";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRoom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRoom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除房间编号为"' + ids + '"的数据项？').then(function () {
        return delRoom(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('user/room/export', {
        ...this.queryParams
      }, `room_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
